# =================================================================================
# remove everything
rm(list=ls())

# ---------------------------------------------------------------------
# Drop outliers in dataset "Data" according to the "v"th column
# at each percentage "p" at bottom and top. The default value of
# p is 0.005. v is a vector of numbers.
# ---------------------------------------------------------------------

outlier <- function(Data, v, p=0.005) {
  out <- c()
  for(i in v) {
    out <- rbind(out, quantile(Data[,i], probs=c(p, 1-p)))
  }
  j <- 1
  for(i in v) {
    Data <- Data[Data[,i]>out[j,1] & Data[,i]<out[j,2], ]; print(dim(Data))
    j <- j+1
  }
  return(Data)
}
# ---------------------------------------------------------------------

# Load packages
library(foreign)
library(plm) # ---------------

# Load data
Data <- read.dta('Ind39.dta')

Data <- outlier(Data, which(names(Data)=="sm"), p=0.005)

# Delete obs according to variable "Foreign"
Data <- subset(Data, F1>=0 & F1<=1 & !is.na(Province) & sm<=1)

# ===================================================================================
# ===================================================================================
# Section One -- Estimation

# Step One
h.lnbe <- mean(log(Data$sm)); h.eta <- - log(Data$sm) + h.lnbe; h.e <- mean(exp(h.eta))
h.betam <- exp(h.lnbe)/h.e

# =============================================
# Step Two
Data.t <- read.dta("Ind39_s_Dt_Est.dta")
Data$wk1 <- Data.t$wk1; Data$wl1 <- Data.t$wl1; Data$wm1 <- Data.t$wm1;

# Generate year dummies
TD <- model.matrix(~as.factor(Data$Year)-1); TD1 <- model.matrix(~as.factor(Data$Year-1)-1)[,-1]

# Define functions: "wphi" and "phi"
wphi <- function(beta) {
  (1-h.betam)*Data$wm1 - h.lnbe - log(Data$ppi1/Data$ppii1) - beta[1]*Data$wk1 - beta[2]*Data$wl1 - TD1%*%beta[3:10] 
}

phi <- function(beta) {
  (1-h.betam)*Data$m1 - h.lnbe - log(Data$ppi1/Data$ppii1) - beta[1]*Data$k1 - beta[2]*Data$l1 - TD1%*%beta[3:10]
}

# -----------------------------------------------
# Optimization

objfn <- function(beta){
  y.star <- Data$y - h.betam*Data$m - beta[1]*Data$k - beta[2]*Data$l - TD%*%beta[3:11]
  p1 <- as.vector(phi(beta)); p2 <- as.vector(wphi(beta)); 
  var.poly <- poly(cbind(p1, Data$F1, p2), degree = 2, raw = TRUE)
  mod1 <- lm(as.vector(y.star)~var.poly+as.factor(Data$city))
  OBJ <- sum(mod1$residuals^2)
  return(OBJ)
}

set.seed(1)
initial <- c(0.05, 0.1, 0.05, 0,0,0,0,0,0,0,0,0)
target <- optim(initial, objfn, method = "Nelder-Mead")

# results - elas
h.betak <- target$par[1]; h.betal <- target$par[2]

G.coef <- function(beta){
  y.star <- Data$y - h.betam*Data$m - beta[1]*Data$k - beta[2]*Data$l - TD%*%beta[3:11]
  p1 <- as.vector(phi(beta)); p2 <- as.vector(wphi(beta)); 
  var.poly <- poly(cbind(p1, Data$F1, p2), degree = 2, raw = TRUE)
  mod1 <- lm(as.vector(y.star)~var.poly+as.factor(Data$city))
  return(mod1)
}
# results - partial effects
coef <- G.coef(target$par)$coef[2:10]
w1 <- as.vector(phi(target$par)); sw1 <- as.vector(wphi(target$par))

p.w  <- coef[1] + 2*coef[2]*w1 + coef[4]*Data$F1 + coef[7]*sw1
p.F  <- coef[3] + coef[4]*w1 + 2*coef[5]*Data$F1 + coef[8]*sw1
p.sw <- coef[6] + coef[7]*w1 + coef[8]*Data$F1 + 2*coef[9]*sw1
# summary(p.w); summary(p.F); summary(p.sw)

# The estimated w and w1
Data$w <- Data$y - h.betak*Data$k - h.betal*Data$l - h.betam*Data$m - TD%*%target$par[3:11] - h.eta
Data$w1 <- phi(target$par); Data$sw1 <- wphi(target$par); Data$eta <- h.eta

# TIL
D <- data.frame(Data[,c('Firm','Year','Province')], pw=p.w, pF=p.F, psw=p.sw)
D <- pdata.frame(D, index = c("Firm", "Year"))
D$pF1 <- lag(D$pF, 1); 

D$temp1 <- ave(D$pF1, D$Year, D$Province, FUN = function(x) sum(x, na.rm = TRUE))
D$temp1[!is.na(D$pF1)] <- D$temp1[!is.na(D$pF1)] - D$pF1[!is.na(D$pF1)]
D$temp2 <- ave(D$pF1, D$Year, D$Province, FUN = function(x) sum(!is.na(x)))
D$temp2[!is.na(D$pF1)] <- D$temp2[!is.na(D$pF1)] - 1
D$sp=D$temp1/D$temp2
p.til <- as.numeric(D$psw*D$sp); summary(p.til)

# ===================================================================================
# ===================================================================================
# Section Two -- Bootstrap

# Calculate residuals and fitted values
resid <- G.coef(target$par)$residuals # ---------------
fit <- G.coef(target$par)$fitted.values # ---------------

# Start the Bootstrap
set.seed(123)
R <- 399

Bpw <- p.w; BpF <- p.F; Bpsw <- p.sw; Bptil <- p.til
Bbeta <- c(h.betak, h.betal, h.betam)
Bcoef <- coef

for(B in 1:R) {
  # Wild Bootstrap
  unif <- runif(length(resid),0,1)
  a <- (1-sqrt(5))/2
  prob.a <- (sqrt(5)+1)/(2*sqrt(5))
  b <- (1+sqrt(5))/2
  # ----------------------------------------
  # step 1
  h.eta.b <- ifelse(unif <= prob.a, a*h.eta, b*h.eta)
  lsm.b <- h.lnbe - h.eta.b
  
  h.lnbe.b <- mean(lsm.b); h.eta.b <- - lsm.b + h.lnbe.b; h.e.b <- mean(exp(h.eta.b))
  h.betam.b <- exp(h.lnbe.b)/h.e.b
  
  resid.b <- ifelse(unif <= prob.a, a*resid, b*resid)
  y.b <- h.betak*Data$k + h.betal*Data$l + h.betam.b*Data$m + fit + TD%*%target$par[3:11] + resid.b
  
  # ----------------------------------------
  # step 2
  
  objfn <- function(beta){
    y.star <- y.b - h.betam*Data$m - beta[1]*Data$k - beta[2]*Data$l - TD%*%beta[3:11]
    p1 <- as.vector(phi(beta)); p2 <- as.vector(wphi(beta)); 
    var.poly <- poly(cbind(p1, Data$F1, p2), degree = 2, raw = TRUE)
    mod1 <- lm(as.vector(y.star)~var.poly+as.factor(Data$city))
    OBJ <- sum(mod1$residuals^2)
    return(OBJ)
  }
  target.b <- optim(initial, objfn, method = "Nelder-Mead")
  
  # results - elas
  h.betak.b <- target.b$par[1]; h.betal.b <- target.b$par[2]
  
  
  G.coef.b <- function(beta){
    y.star <- y.b - h.betam*Data$m - beta[1]*Data$k - beta[2]*Data$l - TD%*%beta[3:11]
    p1 <- as.vector(phi(beta)); p2 <- as.vector(wphi(beta)); 
    var.poly <- poly(cbind(p1, Data$F1, p2), degree = 2, raw = TRUE)
    mod1 <- lm(as.vector(y.star)~var.poly+as.factor(Data$city))
    return(mod1)
  }
  # results - partial effects
  coef.b <- G.coef.b(target.b$par)$coef[2:10]
  w1.b <- as.vector(phi(target.b$par)); sw1.b <- as.vector(wphi(target.b$par))
  
  p.w.b  <- coef.b[1] + 2*coef.b[2]*w1.b + coef.b[4]*Data$F1 + coef.b[7]*sw1.b
  p.F.b  <- coef.b[3] + coef.b[4]*w1.b + 2*coef.b[5]*Data$F1 + coef.b[8]*sw1.b
  p.sw.b <- coef.b[6] + coef.b[7]*w1.b + coef.b[8]*Data$F1 + 2*coef.b[9]*sw1.b
  
  # TIL
  D.b <- data.frame(Data[,c('Firm','Year','Province')], pw=p.w.b, pF=p.F.b, psw=p.sw.b)
  D <- pdata.frame(D.b, index = c("Firm", "Year"))
  D$pF1 <- lag(D$pF, 1); 
  
  D$temp1 <- ave(D$pF1, D$Year, D$Province, FUN = function(x) sum(x, na.rm = TRUE))
  D$temp1[!is.na(D$pF1)] <- D$temp1[!is.na(D$pF1)] - D$pF1[!is.na(D$pF1)]
  D$temp2 <- ave(D$pF1, D$Year, D$Province, FUN = function(x) sum(!is.na(x)))
  D$temp2[!is.na(D$pF1)] <- D$temp2[!is.na(D$pF1)] - 1
  D$sp=D$temp1/D$temp2
  p.til.b <- as.numeric(D$psw*D$sp); summary(p.til)
  
  # Store bootstrap results
  Bpw <- cbind(Bpw, p.w.b); BpF <- cbind(BpF, p.F.b); Bpsw <- cbind(Bpsw, p.sw.b); Bptil <- cbind(Bptil, p.til.b)
  Bbeta <-cbind(Bbeta, c(h.betak.b, h.betal.b, h.betam.b))
  Bcoef <- cbind(Bcoef, coef.b)
  
}

apply(Bbeta, MARGIN = 1, sd)
summary(Bpw[,1]); apply(apply(Bpw, MARGIN = 2, summary), MARGIN = 1, sd)
summary(BpF[,1]); apply(apply(BpF, MARGIN = 2, summary), MARGIN = 1, sd)
summary(Bpsw[,1]); apply(apply(Bpsw, MARGIN = 2, summary), MARGIN = 1, sd)
summary(Bptil[,1]); apply(apply(Bptil, MARGIN = 2, summary), MARGIN = 1, sd)

save(BpF, Bpw, Bpsw, Bptil, Bbeta, Bcoef, file = "Boot_s_Dt_F2.RData")

